
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace 图片操作
{
    public partial class Form1 : Form
    {
        private Mat srcImage;  // 存储原始图像

        public Form1()
        {
            InitializeComponent();
            SetUpUI();
        }

        private void SetUpUI()
        {
            this.Text = "图片操作";
            this.Size = new System.Drawing.Size(1024, 768);

            flowLayoutPanel1.AutoSize = true;
            flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowOnly; // 或 GrowAndShrink
            flowLayoutPanel1.WrapContents = true;
            flowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight;

        }

        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图像文件|*.jpg;*.jpeg;*.png;*.bmp";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    srcImage = Cv2.ImRead(openFileDialog.FileName, ImreadModes.Color);
                    if (!srcImage.Empty())
                    {
                        pictureBox1.Image = BitmapConverter.ToBitmap(srcImage);
                    }
                    else
                    {
                        MessageBox.Show("无法加载图像！");
                    }
                }
            }
        }
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (srcImage == null || srcImage.Empty())
            {
                MessageBox.Show("没有图像可保存！");
                return;
            }

            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "PNG图像|*.png|JPEG图像|*.jpg";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Cv2.ImWrite(saveFileDialog.FileName, srcImage);
                    MessageBox.Show("保存成功！");
                }
            }
        }

        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (srcImage == null || srcImage.Empty())
            {
                MessageBox.Show("请先加载图像！");
                return;
            }

            // 创建缩放后的图像（宽度和高度各为原来的50%）
            Mat resizedImage = new Mat();
            Cv2.Resize(srcImage, resizedImage, new OpenCvSharp.Size(), 0.5, 0.5);

            // 显示缩放后的图像
            pictureBox1.Image?.Dispose();
            pictureBox1.Image = BitmapConverter.ToBitmap(resizedImage);

            // 释放资源
            resizedImage.Dispose();
        }


        /// <summary>
        /// 图片裁剪
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (srcImage == null || srcImage.Empty())
            {
                MessageBox.Show("请先加载图像！");
                return;
            }

            int width = srcImage.Width;
            int height = srcImage.Height;

            // 定义裁剪区域（从坐标(100,100)开始，宽200，高150）
            Rect roi = new Rect(0, 0, width / 2, height / 2);
            Mat croppedImage = new Mat(srcImage, roi);

            // 显示裁剪后的图像
            pictureBox1.Image?.Dispose();
            pictureBox1.Image = BitmapConverter.ToBitmap(croppedImage);

            // 释放资源
            croppedImage.Dispose();
        }
        /// <summary>
        /// 图片裁剪成8个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (srcImage == null || srcImage.Empty())
            {
                MessageBox.Show("请先加载图像！");
                return;
            }

            int totalCols = 4; // 横向切分数量
            int totalRows = 2; // 纵向切分数量
            int pieceWidth = srcImage.Width / totalCols;
            int pieceHeight = srcImage.Height / totalRows;

            List<Mat> croppedImages = new List<Mat>();

            for (int row = 0; row < totalRows; row++)
            {
                for (int col = 0; col < totalCols; col++)
                {
                    Rect roi = new Rect(col * pieceWidth, row * pieceHeight, pieceWidth, pieceHeight);
                    Mat roiMat = new Mat(srcImage, roi);
                    croppedImages.Add(roiMat);
                }
            }

            // 可选：显示第一个裁剪图到 pictureBox1
            if (croppedImages.Count > 0)
            {
                pictureBox1.Image?.Dispose();
                pictureBox1.Image = BitmapConverter.ToBitmap(croppedImages[0]);
            }

            // 后续可对 croppedImages 进行保存、处理等操作
            // 清空 flowLayoutPanel1 中已有的控件
            flowLayoutPanel1.Controls.Clear();
            flowLayoutPanel1.AutoScroll = true;
            flowLayoutPanel1.AutoSize = true;
            flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowOnly;
            flowLayoutPanel1.WrapContents = true;
            
            // 将裁剪后的图像添加到 flowLayoutPanel1
            foreach (var mat in croppedImages)
            {
                Bitmap bitmap = BitmapConverter.ToBitmap(mat);
                PictureBox pictureBox = new PictureBox();
                pictureBox.Image = bitmap;
                pictureBox.SizeMode = PictureBoxSizeMode.AutoSize; // 自动适应图片大小
                pictureBox.BorderStyle = BorderStyle.FixedSingle;

                flowLayoutPanel1.Controls.Add(pictureBox);
            }
            // 注意：使用完后记得释放资源
            foreach (var img in croppedImages)
            {
                img.Dispose();
            }
        }
    }
}
